/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.restaurant.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.modules.restaurant.entity.PurchaseCommodity;
import org.springblade.modules.restaurant.excel.PurchaseCommodityExcel;
import org.springblade.modules.restaurant.mapper.PurchaseCommodityMapper;
import org.springblade.modules.restaurant.service.IPurchaseCommodityService;
import org.springblade.modules.restaurant.vo.PurchaseCommodityVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 采购货物 服务实现类
 *
 * @author Blade
 * @since 2025-01-21
 */
@Service
public class PurchaseCommodityServiceImpl extends BaseServiceImpl<PurchaseCommodityMapper, PurchaseCommodity> implements IPurchaseCommodityService {

	@Override
	public IPage<PurchaseCommodityVO> selectPurchaseCommodityPage(IPage<PurchaseCommodityVO> page, PurchaseCommodityVO purchaseCommodity) {
		return page.setRecords(baseMapper.selectPurchaseCommodityPage(page, purchaseCommodity));
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void importStock(List<PurchaseCommodityExcel> listExcel) {
		List<PurchaseCommodity> list = new ArrayList<>();
		for (PurchaseCommodityExcel excel : listExcel) {
			PurchaseCommodity purchaseCommodity = new PurchaseCommodity();
			purchaseCommodity.setId(Long.parseLong(excel.getId()));
			BigDecimal stockNumber = ObjectUtil.defaultIfNull(excel.getStockNumber(), BigDecimal.ZERO);
			BigDecimal referencePrice = ObjectUtil.defaultIfNull(excel.getReferencePrice(), BigDecimal.ZERO);
			// 库存价值 = 库存数量 * 参考单价
			BigDecimal stockValue = stockNumber.multiply(referencePrice);

			purchaseCommodity.setStockNumber(stockNumber);
			purchaseCommodity.setReferencePrice(referencePrice);
			purchaseCommodity.setStockValue(stockValue);

			list.add(purchaseCommodity);
		}
		updateBatchById(list);
	}

}
